#define _CRT_SECURE_NO_WARNINGS

#include "SeqList.h"

void SL_Init(SL *s)
{
	s->arr = (SLDataType*)malloc(sizeof(SLDataType) * 4);
	if (s->arr == NULL)
	{
		perror("malloc error");
		return;
	}
	s->size = 0;
	s->capacity = 4;
}

static void SL_CheckCapacity(SL* s)
{
	if (s->capacity == s->size)
	{
		SLDataType* tmp = (SLDataType*)realloc(s->arr, sizeof(SLDataType) * (s->capacity * 2));
		if (tmp == NULL)
		{
			perror("relloc error");
			return;
		}
		s->arr = tmp;
		s->capacity *= 2;
	}
}

void SL_PushBack(SL* s, SLDataType d)
{
	/*SL_CheckCapacity(s);
	s->arr[s->size++] = d;*/
	SL_Insert(s, s->size, d);
}

void SL_PushFront(SL* s, SLDataType d)
{
	SL_Insert(s, 0, d);
}

void SL_Print(SL* s)
{
	for (int i = 0; i < s->size; i++)
	{
		printf("%d ", s->arr[i]);
	}
	printf("\n");
}

void SL_Insert(SL* s, int pos, SLDataType d)
{
	assert(s);
	assert(0 <= pos && pos <= s->size);

	SL_CheckCapacity(s);

	int end = s->size;
	while (end>pos)
	{
		s->arr[end] = s->arr[end - 1];
		end--;
	}
	s->arr[pos] = d;
	s->size++;
}

void SL_PopFront(SL* s)
{
	//assert(s);
	//assert(s->size >= 0);
	//for (int i = 1; i < s->size; i++)
	//{
	//	s->arr[i - 1] = s->arr[i];
	//}
	//s->size--;
	SL_Erase(s, 0);
}

void SL_PopBack(SL* s)
{
	/*assert(s);
	assert(s->size >= 0);
	s->size--;*/
	SL_Erase(s, s->size-1);
}

void SL_Erase(SL* s, int pos)
{
	assert(s);
	assert(pos>=0 && pos<(s->size));
	int start = pos;
	while (start < s->size-1)
	{
		s->arr[start] = s->arr[start + 1];
		start++;
	}
	s->size--;
}

int SL_Find(SL* s, SLDataType d)
{
	assert(s);
	for (int i = 0; i < s->size; i++)
	{
		if (s->arr[i] == d)
		{
			return i;
		}
	}
	return -1;
}

void SL_Modify(SL* s, int pos, SLDataType d)
{
	assert(s);
	assert(pos >= 0 && pos < (s->size));

	s->arr[pos] = d;
}